<?php defined('SYSPATH') or die('No direct script access.');

class Songs_Model extends Model {

	protected $temp_filename;
	protected $lowBitFile;
	protected $highBitFile;

	public function __construct() {
		$this->temp_filename = '';
		$this->db = Database::instance();
	}

	public function count_songs()
	{
		$query = $this->db->select('track_no')->get('songs');
		return $query->count();
	}

	public function loads() {
		$sql = '
			SELECT *
			FROM songs 
			ORDER BY title;
    	';
		$query = $this->db->query($sql);
		return $query->result(FALSE);
	}

	public function load($album_id,$track_id) {
		$sql = '
			SELECT * 
			FROM songs 
			WHERE album_id=? AND track_no=?;
    	';
		$query = $this->db->query($sql, array($id));
		return $query->result(FALSE);
	}

	public function get_song_show($limit, $offset){
//		$sql = "
//			SELECT 
//			  songs.track_no,
//			  songs.title,
//			  songs.duration,
//			  songs.sample_file,
//			  songs.low_bit_rate_file,
//			  songs.high_bit_rate_file,
//			  songs.created,
//			  songs.updated,
//			  albums.title AS album ,
//			  genes.name AS gene
//			FROM
//			  songs
//			  INNER JOIN albums ON (songs.album_id = albums.id)
//			  INNER JOIN genes ON (songs.gene_id = genes.id)
//			ORDER BY
//			  songs.title
//			LIMIT ? , ?
//		";

		$sql = "SELECT 
				  songs.title,
				  songs.duration,
				  SUBSTR(songs.sample_file, 20) AS sample_file,
				  SUBSTR(songs.low_bit_rate_file, 20) AS low_bit_rate_file,
				  SUBSTR(songs.high_bit_rate_file, 20) AS high_bit_rate_file,
				  songs.created,
				  songs.updated,
				  songs.track_no,
				  artists.name AS artist,
				  albums.title AS album,
				  genes.name AS gene
				FROM
				  songs
				  INNER JOIN albums ON (songs.album_id = albums.id)
				  INNER JOIN genes ON (songs.gene_id = genes.id)
				  INNER JOIN artists_songs ON (songs.album_id = artists_songs.album_id)
				  AND (songs.track_no = artists_songs.track_no)
				  INNER JOIN artists ON (artists_songs.artist_id = artists.id)
				ORDER BY
				  songs.title
				LIMIT ? , ?;
		";
		
		$query = $this->db->query($sql,array($offset, $limit));
		return $query->result(FALSE);
	}

	public function browse($limit, $offset)
	{
		$sql = '
			SELECT * 
			FROM songs 
			ORDER BY title
			LIMIT ?, ?;
    	';
		$result = $this->db->query($sql, array($offset, $limit))->result(FALSE);
		return $result;
	}

	public function save($data,$mode='add'){
		$this->db->query('BEGIN');
		try {
			if ($mode=='add') {
				$sql = 'INSERT INTO songs(album_id, track_no, title, gene_id, duration, sample_file, low_bit_rate_file, high_bit_rate_file, created ) VALUES(?,?,?,?,?,?,?,?,CURRENT_TIMESTAMP());';
				$query = $this->db->query($sql, array($data['album_id'], $data['track_no'], $data['title'],$data['gene_id'],$data['duration'],$data['sample_file'],$data['low_bit_rate_file'],$data['high_bit_rate_file']));
				
				//insert artist_song
				$sql = 'INSERT INTO artists_songs(artist_id, album_id, track_no, created) VALUES(?,?,?,CURRENT_TIMESTAMP());';
				$query = $this->db->query($sql,array($data['artist_id'],$data['album_id'],$data['track_no']));
			}
			else {
				if (empty($data['cover_picture'])) {
					$sql = 'UPDATE albums SET title=?, released_date=?, updated=CURRENT_TIMESTAMP() WHERE id=?;';
					$query = $this->db->query($sql, array($data['title'], $data['released_date'], $data['id']));
				}
				else {
					$sql = 'UPDATE albums SET title=?, cover_picture=?, released_date=?, updated=CURRENT_TIMESTAMP() WHERE id=?;';
					$query = $this->db->query($sql, array($data['title'], $data['cover_picture'], $data['released_date'], $data['id']));
				}

			}
			$this->db->query('COMMIT');
			return true;
		} catch (Exception $e) {
			$this->db->query('ROLLBACK');
			Kohana::log('error', $e);
			return false;
		}
	}

	public function file_validate($file_name) {
		//		$_FILES = Validation::factory($_FILES)
		//		->add_rules('song',
		//        'upload::valid',
		//        'upload::type[mp3,ogg,wav]',
		//        'upload::size[10M]');
			
		//		if ($_FILES->validate())
		//		{

		$config = Kohana::config('hsm');
		// Temporary file name
		$new_filename = uniqid() . '.mp3';
		$this->temp_filename = upload::save($file_name, $new_filename, $config['upload_songs']);


		//			$config = Kohana::config('hsm');
		//
		//			Kohana::log("debug","upload file " . $file_name);
		//
		// Temporary file name
		//			$this->temp_filename = upload::save($file_name,uniqid().'.mp3',"media/upload/songs/");
		//
		//			if (file_exists($this->temp_filename)) {
		//				// Resize, sharpen, and save the image
		//				Image::factory($this->temp_filename)
		//				->resize($config['image_max_width'], $config['image_max_height'], Image::AUTO)
		//				->save($config['upload_albums'].basename($this->temp_filename));
		//
		//				// Remove the temporary file
		//				unlink($this->temp_filename);
		//			$this->temp_filename = $config['upload_songs'].basename($this->temp_filename);
		//			}
		//			else {
		//				$this->temp_filename = '';
		//			}
		//		}
		return $_FILES;
	}

	public function get_filename() {
		return $this->temp_filename;
	}
}